package cn.csc.module.pay.config;

import cn.csc.framework.common.util.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * rocketmq消息分区
 * @author liuchuang
 * @version 1.0
 * @date 2023/5/11 14:02
 * @modify
 */
@Slf4j
@Component
public class OrderlyMessageQueueSelector implements MessageQueueSelector {

    @Override
    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
        // arg示例：{"ORIGIN_MESSAGE_ID":"1874018201605632001","id":"523ca15f-0f8a-14cb-a44d-dbbe17c09a70","contentType":"application/json"
        // ,"TAGS":"jzbOrderTag","tenant-id":130,"target-protocol":"kafka","timestamp":1735635731512}
        log.info("OrderlyMessageQueueSelector arg: {}", JsonUtils.toJsonString(arg));
        // msg示例：{"topic":"jzb_order_send","flag":0,"properties":{"id":"71cdb118-dd0b-8380-0a39-fce6a68f8903","WAIT":"true",
        // "contentType":"application/json","TAGS":"jzbOrderTag","tenant-id":"130","target-protocol":"kafka","timestamp":"1735635731512"},
        // "body":"eyJpZCI6IjE4NzQwMTgyMDE2MDU2MzIwMDEiLCJzZXEiOiIyMDI0MTIzMTE3MDIxMTQ4OTg5MjIzIiwidHlwZUlkIjoiMSJ9","transactionId":null,
        // "tags":"jzbOrderTag","keys":null,"delayTimeLevel":0,"waitStoreMsgOK":true,"buyerId":null}
        log.info("OrderlyMessageQueueSelector msg: {}", JsonUtils.toJsonString(msg));
        int queueIndex = Math.abs(arg.hashCode()) % mqs.size();
        // BigInteger id = new BigInteger(((MessageHeaders) arg).get(MessageConst.PROPERTY_ORIGIN_MESSAGE_ID).toString());
        // int index = id.remainder(BigInteger.valueOf(mqs.size())).intValue();

        return mqs.get(queueIndex);
    }

}
